package com.hiray.demos.entry

import android.content.Intent
import android.content.res.AssetManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import com.hiray.demos.BuildConfig
import com.hiray.demos.R
import kotlinx.android.synthetic.main.activity_browser_launch_app.*
import java.io.File
import java.io.FileOutputStream

/**
 * 用手机默认浏览器加载asset下的browser_to_app.html文件，进入html页面后点击超链接，响应后回到本页面接收信息
 */
class BrowserLaunchAppActivity : AppCompatActivity() {

    private val TAG = "BrowserAppActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_browser_launch_app)
        button2.setOnClickListener({
            writeToFile()
            WebViewActivity.openUrl(this@BrowserLaunchAppActivity, "file:////android_asset/browser_to_app.html")
        })
        var data = intent.data
        if (data != null)
            Log.i("BrowserLaunchApp--", data.getQueryParameter("name") + data.getQueryParameter("age"))
    }

    private fun writeToFile() {
        val htmlFile = File(Environment.getExternalStorageDirectory().absolutePath + "/browser_to_app.html")
        Log.i(TAG, "writeToFile: ${htmlFile.absolutePath}")
        if (htmlFile.exists()) {
            htmlFile.delete()
            htmlFile.createNewFile()
        }
        val fos = FileOutputStream(htmlFile)
        val fis = assets.open("browser_to_app.html")
        fis.copyTo(fos)
        openFileWithBrowser(htmlFile.absolutePath)
    }

    private fun openFileWithBrowser(path: String) {
        var uri = Uri.parse(path).buildUpon()
                .encodedAuthority(BuildConfig.APPLICATION_ID)
                .scheme("content")
                .encodedPath(path)
                .build()
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(uri, "text/html")
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        var data = intent.data
        if (data != null)
            Log.i("BrowserLaunchApp", data.getQueryParameter("name") + data.getQueryParameter("age"))
    }
}
